package com.hqd.ch03.v31.web.servlet;


import com.hqd.ch03.v31.context.stereotype.Controller;
import com.hqd.ch03.v31.web.method.HandlerMethod;
import com.hqd.ch03.v31.web.servlet.handler.RequestMappingHandlerMapping;
import org.reflections.Reflections;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

public class DispatcherServlet extends HttpServlet {
    private static final String PREFIX = "/views/";
    private static final String SUFFIX = ".jsp";
    private RequestMappingHandlerMapping rmhm = new RequestMappingHandlerMapping();


    @Override
    public void init(ServletConfig config) throws ServletException {
        Reflections reflections = new Reflections("com.hqd.ch03.test.web.v31");
        // 获取指定包下所有类
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Controller.class);
        for (Class<?> clazz : classes) {
            try {
                rmhm.init(clazz.newInstance());
            } catch (Exception e) {
                throw new RuntimeException("class [" + clazz.getName() + "] create is error，because：" + e.getMessage());
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HandlerMethod handler = null;
        try {
            handler = this.rmhm.getHandler(request);
            if (handler == null) {
                response.sendError(404);
            } else {
                Object result = handler.getMethod().invoke(handler.getBean(), request, response);
                if (result instanceof String) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher(PREFIX + result + SUFFIX);
                    dispatcher.forward(request, response);
                }
            }
        } catch (Exception e) {
            response.sendError(500);
        }

    }
}
